<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="账户名称" prop="loginName">
        <el-input v-model="queryParams.loginName" placeholder="请输入账户名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>


      <el-form-item label="性别" prop="gender">
          <el-select v-model="queryParams.gender" placeholder="请选择" clearable>
             <el-option v-for="item in dicts.sys_user_sex"  :key="item.value"  :label="item.label"  :value="item.value">
             </el-option>
           </el-select>
      </el-form-item>


     <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable>
             <el-option v-for="item in dicts.sys_normal_disable" :key="item.value"  :label="item.label"  :value="item.value">
             </el-option>
           </el-select>
      </el-form-item>


      <el-form-item label="创建时间" prop="dateTimeRange">
          <el-date-picker
                v-model="dateTimeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                 value-format="yyyy-MM-dd">
              </el-date-picker>
       </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能区 -->
    <el-row>
      <el-col :span="24">
         <el-button type="primary" size="small" v-if="isRoot"  @click="handlerAdd()" >新增</el-button>
         <el-button type="warning" size="small" v-if="isRoot"  @click="handlerUpdate()" :disabled="single" >修改</el-button>
         <el-button type="success" size="small"   @click="handlerExcel()"  >导出</el-button>
      </el-col>
    </el-row>


    <el-table :data="tableData.rows" border style="width: 100%"  v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="selectable"/>
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="loginName" label="账户" width="180" />
      <el-table-column label="性别" width="180">
        <template slot-scope="scope">
          <el-tag  v-for="item in dicts.sys_user_sex"  :key="item.id" v-if="item.value=== scope.row.gender" :type="item.listClass" >{{item.label}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="180">
        <template slot-scope="scope">
          <el-tag  v-for="item in dicts.sys_normal_disable" :key="item.id" v-if="item.value=== scope.row.status" :type="item.listClass" >{{item.label}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="头像" width="180">
        <template slot-scope="scope">
         <!-- <img :src="scope.row.avatar" width="150"> -->
          <el-image
             style="width: 100px; height: 100px"
             :src="scope.row.avatar"
             :preview-src-list="[scope.row.avatar]">
           </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" align="left" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="isRoot || scope.row.loginName===name" size="mini" type="text" icon="el-icon-edit" @click="handlerUpdate(scope.row)">修改</el-button>

          <el-button v-if="isRoot && scope.row.id!==1 && scope.row.status==='0'" size="mini"  type="text" icon="el-icon-delete" style="color:red;" @click="handlerDisable(scope.row)">停用</el-button>
          <el-button v-else-if="isRoot && scope.row.id!==1 && scope.row.status==='1'" size="mini" type="text" icon="el-icon-video-play" @click="handlerEnable(scope.row)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination v-if="tableData.total>0" :current-page="queryParams.page" :page-sizes="[1, 5, 10, 20,30,50,100]"
      :page-size="queryParams.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 新增和修改的对话框 -->
    <!-- 对话框-->
    <el-dialog 	v-bind:title="title"  :visible.sync="dialogVisible"  width="500px"  :close-on-click-modal="false"   >
      <!-- 内容 -->
    				<el-form ref="form" :model="form" label-width="80px">

    				  <el-form-item v-if="form.id" label="登录账号" >
    				     <b>{{form.loginName}}</b>
    				  </el-form-item>
              <el-form-item v-else label="登录账号" prop="loginName" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }, { validator: accountExistsValid, trigger: 'blur' }]">
                <el-input v-model="form.loginName"></el-input>
              </el-form-item>


              <el-form-item v-if="isRoot" label="登录密码" prop="loginPwd" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]">
                <el-input  show-password v-model="form.loginPwd"></el-input>
              </el-form-item>

              <el-form-item v-if="isRoot" label="确认密码" prop="loginPwdConfirm" :rules="[{ required: true, message: '不能为空', trigger: 'blur' },{validator: validatePass2, trigger: 'blur'}]">
                <el-input  show-password v-model="form.loginPwdConfirm"></el-input>
              </el-form-item>

    				  <el-form-item label="性别">
    				    <el-radio-group v-model="form.gender">
    				       <el-radio v-for="item in dicts.sys_user_sex"  :key="item.id" :label="item.value">{{item.label}}</el-radio>
    				    </el-radio-group>
    				  </el-form-item>

              <el-form-item label="状态" v-if="isRoot">
                <el-radio-group v-model="form.status">
                    <el-radio v-for="item in dicts.sys_normal_disable" :key="item.id" :label="item.value">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>


              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  :action="avatarUploadUrl"
                  :headers="tokenHeader"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="form.avatar" :src="form.avatar" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>


    				</el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click="saveFormBefore">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {dataApi, addApi, updateApi, accountExists, findByIdApi, changeStatusApi} from '@/api/employee.js'
  import {dataDictTypes } from '@/api/dictdata.js'
  import { mapGetters } from 'vuex'
  //图片上传配置
  import {adminImageUploadUrl} from '@/settings.js'
  import { getToken } from '@/utils/auth'



  export default {
    // 计算属性(java中自定义get方法)
    computed: {
      ...mapGetters([
        'isRoot',
        'name'
      ]),
      //自定义方法（构造令牌）
      tokenHeader(){
        return {
          'satoken' : + getToken()
        }
      }
    },
    created() {
      //页面初始化操作，这个方法只会被调用一次
      this.fetchData()
      this.fetchDictTypes()
    },
    data() {
      return {
         avatarUploadUrl: adminImageUploadUrl,

         //日期变量
         dateTimeRange:[],

         loading: false,
         // 表单查询条件对象
         queryParams:{
           pageNumber: 1,
           pageSize: 10
         },
         // 分页表格分页的结果对象
          tableData: {
            total: 0,
            rows: []
          },
          //表格选中的对象
          mutilrows:[],
          //表格选中对象的主键的值
          ids: [],
          //编辑按钮禁用
          single: true,
          //对话框的变量
          title: '添加数据',
          dialogVisible: false,
          form: {
            //图片必须要先定义
            avatar: undefined,
            gender: '0',
            status: '0'
          },
          //数据字典返回结果
          dicts: {}
      }
    },
     methods:{
       //表格，是否允许被选中， 返回true允许，否则不允许
       selectable(row,index){
         return  row.id!==1
       },
       //验证账号是否存在
       accountExistsValid (rule, value, callback)  {
            accountExists(value).then(resp=> {
              console.log(resp)
              if(resp.data){
                 callback(new Error( resp.data));
              }else{
                 callback();
              }
            })
        },
        //验证两次密码不一致
        validatePass2 (rule, value, callback)  {
          if (value === '') {
            callback(new Error('请再次输入密码'));
          } else if (value !== this.form.loginPwd) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
       },
       //查询数据字典的值
       fetchDictTypes() {
         const params= ['sys_user_sex', 'sys_normal_disable']
         dataDictTypes(params).then(resp=> {
            this.dicts = resp.data
         })
       },
       //点击新增按钮
       handlerAdd(){
         //显示对话框
         this.dialogVisible =true
         this.title='添加数据'
       },
       //点击修改按钮
       handlerUpdate(row){
         let id;
         if(row){
           id=row.id
         }else{
           id=this.ids[0]
         }
         //根据主键查询数据，回填充form表单中
         findByIdApi(id).then(resp=> {
           this.form = resp.data

           this.dialogVisible =true
           this.title='编辑数据'
         })
       },
       //选中表格值的变化事件
        handleSelectionChange(val) {
          console.log(val)
            this.mutilrows = val;
            this.ids=val.map(s=> s.id);
            this.single = val.length!==1
        },
       // 每页几笔发生变化
        handleSizeChange(val) {
           this.queryParams.page=1
           this.queryParams.size=val
           // 重新查询
           this.fetchData()
       },
       // 当前页发生变化
       handleCurrentChange(val) {
           this.queryParams.page=val
            // 重新查询
            this.fetchData()
       },
       // 获取后台的查询数据
       fetchData(){
         this.loading=true
         //因为我这里有时间，所以添加日期
         delete this.queryParams.beginTime
         delete this.queryParams.endTime
         if(this.dateTimeRange && this.dateTimeRange.length===2){
           this.queryParams.beginTime = this.dateTimeRange[0]
           this.queryParams.endTime = this.dateTimeRange[1]
         }

         dataApi(this.queryParams).then(resp=> {
             this.tableData.total = resp.data.total
             this.tableData.rows = resp.data.list
             this.loading =false
         })
       },
       //点击搜索按钮
       handleQuery(){
         this.queryParams.page =1
         this.fetchData()
       },
       //重置表单
       resetForm(){
          //清空验证规则样式
          this.$refs['form'].resetFields();
          //清除数据
          this.form={
            //图片必须要先定义，不定义图片不能显示的
            avatar: undefined,
            gender: '0',
            status: '0'
          }
          //关闭对话框
          this.dialogVisible =false
       },
       //提交保存数据之前验证
       saveFormBefore(){
          //验证数据是否都有效了
           this.$refs['form'].validate((valid) => {
            if (valid) {
               //验证成功
               this.$confirm('确定要保存数据吗?', '提示', {
                         confirmButtonText: '确定',
                         cancelButtonText: '取消',
                         type: 'warning'
                       }).then(() => {
                          //提交
                           this.saveForm();

                       }).catch(() => {
                         //不提交操作
                       });

            } else {
              return false;
            }
          });
       },
       //向后台提交数据
        saveForm(){
          //修改
          let saveApi;
          if(this.form.id){
             saveApi= updateApi;
          }else{
             saveApi =addApi
          }

          saveApi(this.form).then(resp=> {
              this.$message({message: '操作成功', type: 'success'});
              //关闭窗体
              this.resetForm()
              //重新查询数据
              this.fetchData()
          })

        },
       //图片发送给java后台，返回的结果
        handleAvatarSuccess(res, file) {
            this.form.avatar = res.data.image_url
         },
         //图片上传之前的验证
         beforeAvatarUpload(file) {
           const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
           const isLt2M = file.size / 1024 / 1024 < 2;

           if (!isImage) {
             this.$message.error('上传图片只能是 JPG、PNG 格式!');
           }
           if (!isLt2M) {
             this.$message.error('上传头像图片大小不能超过 2MB!');
           }
           return isImage && isLt2M;
         },
         //停用账户
         handlerDisable(row){
           this.confirmTips('确定要停用该账户吗？',()=>{
             this.changeStates(row.id,'1')
           })
         },
         //启用账户
         handlerEnable(row){
           this.confirmTips('确定要启用该账户吗？',()=> {
             this.changeStates(row.id,'0')
           })
         },
         //更改账号状态
         changeStates(id,status){
            changeStatusApi( {'id': id, 'status': status}).then(resp=> {
              this.$message({message: '操作成功', type: 'success'});
              //重新查询数据
              this.fetchData()
            })
         },
         //导出excel
         handlerExcel(){
           if(this.ids && this.ids.length>0){
             this.download('/api/employee/download/choice', {'ids':this.ids},`员工列表_${new Date().getTime()}.xlsx`)
           }else{
             this.download('/api/employee/download', this.queryParams,`员工列表_${new Date().getTime()}.xlsx`)
           }

         }
     }
  }
</script>

<style>
</style>
